package com.midian.common.pay.tenpay.xmlutil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.regex.Matcher;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


/**
 * 解析接收到的微信xml，返回消息对象
 * @author 飞
 *
 */
public class ReceiveXmlUtils {
	
	/**
	 * 流转字符串
	 * @param is 流
	 * @return
	 * @throws IOException
	 */
	public static String getStreamToString(InputStream is) throws IOException{
		StringBuilder sb = new StringBuilder();
		try(BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
			String s = "";
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 解析微信xml消息
	 * @param <T>
	 * @param strXml
	 * @return
	 */
	public static <T> T getMsgEntity(String strXml, Class<T> clazz){
		T msg = null;
		try {
			if (strXml.length() <= 0 || strXml == null)
				return null;			 
			// 将字符串转化为XML文档对象
			Document document = DocumentHelper.parseText(strXml);
			// 获得文档的根节点
			Element root = document.getRootElement();
			// 遍历根节点下所有子节点
			Iterator<?> iter = root.elementIterator();
			//返回类
			msg = clazz.newInstance();
			// 遍历所有结点	
			//利用反射机制，调用set方法
			while(iter.hasNext()){
				Element ele = (Element)iter.next();
				//获取set方法中的参数字段（实体类的属性）
				Field field = clazz.getDeclaredField(ele.getName());
				//正则替换
				String fieldName = ele.getName().replaceFirst("_\\d+", Matcher.quoteReplacement("_$n"))
						   .replaceFirst("_\\d+", Matcher.quoteReplacement("_$m"));
				//获取set方法，field.getType())获取它的参数数据类型
				Method method = clazz.getDeclaredMethod("set"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1), field.getType());
				//调用set方法
				method.invoke(msg, ele.getText());
			}
		} catch (Exception e) {
		//	System.out.println("xml 格式异常: "+ strXml);
			e.printStackTrace();
		}
		return msg;
	}
}
